/**
 * FacebookClient
 *
 * @author Jackie Gleason
 * @version 1.0
 */
package org.sociald.facebook.client

import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import com.google.code.facebookapi.FacebookJsonRestClient
import org.json.JSONArray
import org.json.JSONObject
import com.google.code.facebookapi.FacebookException
import org.json.JSONException
import org.joda.time.DateTime

public class FacebookClient {
    private static final String FACEBOOK_USER_CLIENT = "facebook.user.client";
    private static final String FACEBOOK_API_KEY = "3f0d311e56d6af31a74603e142997063";
    private static final String FACEBOOK_SECRET = "26552151c07e0552c6fca69818c10e13";
    private Log logger = LogFactory.getLog(FacebookClient.class);
    FacebookJsonRestClient client;
    public void setClient(String sessionId) {
        client = new FacebookJsonRestClient(FACEBOOK_API_KEY, FACEBOOK_SECRET, sessionId);
    }
    public List<String> getMessagesByDate(String userId, DateTime endTime) throws FacebookException{
         return getMessagesByDate(userId,endTime.toDate().getTime())
    }
    public List<String> getMessagesByDate(String userId, Long endTime) throws FacebookException{
        List<String> messagesToReturn = new ArrayList<String>()
        if (!client) {
            throw new RuntimeException("The facebook client was null")
        }
        try {
            String time = endTime.toString()
            if(time.size()>10){
                time = time.substring(0,10)
            }
            String queryToGetFriendName = getMessagesQuery(userId, time);
            // org.json.JSONArray friendsListArray = (org.json.JSONArray)
            def sqlResponse = client.fql_query(queryToGetFriendName);
            if(!sqlResponse){
                return
            }
            if (sqlResponse instanceof JSONArray) {
                JSONArray arrayResponse = (JSONArray) sqlResponse;
                //TODO: Why is this private is there a way around interacting directly?
                arrayResponse.myArrayList.each{def obj ->
                    if(obj instanceof JSONObject){
                        JSONObject jsonObj = (JSONObject)obj
                        messagesToReturn.add(jsonObj.get("message").toString());
                    }

                }
            }
        }
        catch (FacebookException ex) {
            throw ex;

        }
        catch (JSONException jex) {
            System.out.println(">Error: Couldn't talk to JSON> " + jex);
        }
        return messagesToReturn;
    }
    private String getMessagesQuery(String id, String time){
        return "SELECT message,permalink,updated_time FROM stream WHERE source_id =${id} and updated_time > '${time}' LIMIT 10"
    }
}
